<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 用戶管理
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <!-- <el-button
                    type="primary"
                    icon="el-icon-delete"
                    class="handle-del mr10"
                    @click="delAllSelection"
                >批量停用</el-button>
                <el-select v-model="query.address" placeholder="地址" class="handle-select mr10">
                    <el-option key="1" label="广东省" value="广东省"></el-option>
                    <el-option key="2" label="湖南省" value="湖南省"></el-option>
                </el-select> -->
                <el-input v-model="query.name" placeholder="输入用户名或手机号查找" class="handle-input mr10"></el-input>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
            </div>
            <el-table
                :data="tableData"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column prop="id" label="ID" width="55" align="center"></el-table-column>
                <el-table-column prop="name" label="用户名"></el-table-column>
                <el-table-column prop="phone" label="手机号"></el-table-column>
                <el-table-column prop="trueName" label="真实姓名"></el-table-column>
                <el-table-column label="头像(查看大图)" align="center">
                    <template slot-scope="scope">
                        <el-image
                            class="table-td-thumb"
                            :src="scope.row.header"
                            :preview-src-list="[scope.row.header]"
                        ></el-image>
                    </template>
                </el-table-column>
                <el-table-column prop="signature" label="个性签名"></el-table-column>
                <el-table-column prop="emergencyName" label="紧急联系人"></el-table-column>
                <el-table-column prop="emergencyContacts" label="紧急联系电话"></el-table-column>
                <el-table-column label="禁用操作" width="180" align="center">
                    <template slot-scope="scope">
                          <el-switch :value="scope.row.isDelete == 1?true:false" inline-prompt @change="handleBan(scope.$index, scope.row)" class="switch" 
                          active-color="#ff4949"
                          ></el-switch>
                    </template>
                </el-table-column>
            </el-table>

            <!-- <div class="pagination">
                <el-pagination
                    background
                    layout="total, prev, pager, next"
                    :current-page="query.pageIndex"
                    :page-size="query.pageSize"
                    :total="pageTotal"
                    @current-change="handlePageChange"
                ></el-pagination>
            </div> -->
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑" :visible.sync="editVisible" width="30%">
            <el-form ref="form" :model="form" label-width="70px">
                <el-form-item label="用户名">
                    <el-input v-model="form.name"></el-input>
                </el-form-item>
                <el-form-item label="地址">
                    <el-input v-model="form.address"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
// import { fetchData } from '../../api/index';
import axios from '../../axios/index';
export default {
    name: 'basetable',
    data() {
        return {
            query: {
                pageIndex: 1,
                pageSize: 10
            },
            tableData: [],
            multipleSelection: [],
            delList: [],
            editVisible: false,
            pageTotal: 0,
            form: {},
            idx: -1,
            id: -1
        };
    },
    created() {
        this.getData();
    },
    methods: {
        getData() {
            axios.get('/manager/user/check', {})
            .then(response => {
                const res = response.data;
                
                // if (res.code === '200') {
                    // 對返回的數據進行處理，為 header 添加完整的 URL 前綴
                    this.tableData = res.map(item => {
                        return {
                            ...item,
                            header: item.header ? `http://106.52.12.104:8089${item.header}` : '' // 拼接頭像路徑
                        };
                    });
                    // this.pageTotal = res.pageTotal || res.data.length;   
                    // console.log(this.tableData[2].openid)

            })
            .catch(error => {
                console.error("获取数据失败: ", error);
            });
        },

        // 触发搜索按钮    
        handleSearch() {
            axios.get('/manager/user/check', {})
                .then(response => {
                    const res = response.data;
                    console.log(res)
                    // 將符合條件的用戶篩選出來
                    this.tableData = res.filter(item => {
                        const searchText = this.query.name || '';  // 用戶輸入的查找內容
                        // const addressText = this.query.address || ''; // 用戶選擇的地址
                        return (
                            item.name.includes(searchText) || 
                            item.phone !== null && item.phone.includes(searchText)
                            // (item.trueName && item.trueName.includes(searchText)) || 
                            // (item.signature && item.signature.includes(searchText)) ||
                            // (addressText ? item.address === addressText : true) // 地址篩選
                        );
                    });
                    this.tableData = this.tableData.map(item => {
                        return {
                            ...item,
                            header: item.header ? `http://106.52.12.104:8089${item.header}` : '' // 拼接頭像路徑
                        };
                    });
                    // 更新總條數
                    this.pageTotal = this.tableData.length;
                })
                .catch(error => {
                    console.error("模糊查找失败: ", error);
                });
        },
        // 禁用操作
        handleBan(index, row) {
            console.log("DAD")
            // 二次确认禁用或解除禁用
            if (row.isDelete) {
                // 解除禁用
                this.$confirm('确定要解除禁用吗？', '提示', {
                type: 'warning'
                })
                .then(() => {
                // Send openid to backend
                console.log(this.tableData)
                console.log(index)
                const openid = this.tableData[index].openid; // Access openid from tableData
                console.log(openid)
                axios.get(`/manager/user/revive?openid=${openid}`, {})
                    .then(response => {
                    console.log(response, "解除禁用成功");
                    this.$message.success('解除禁用成功');
                    this.getData();
                    })
                    .catch(error => {
                    console.error(error);
                    this.$message.fail('解除禁用失敗');
                    });
                })
                .catch(() => {});
            } else {
                // 禁用
                this.$confirm('确定要禁用吗？', '提示', {
                type: 'warning'
                })
                .then(() => {
                // Send openid to backend
                console.log(this.tableData)
                console.log(index)
                const openid = this.tableData[index].openid; // Access openid from tableData
                console.log(openid)
                axios.get(`/manager/user/delete?openid=${openid}`, {})
                    .then(response => {
                    console.log(response, "禁用成功");
                    this.$message.success('禁用成功');
                    this.getData();
                    })
                    .catch(error => {
                    console.error(error);
                    this.$message.fail('禁用失敗');
                    });
                })
                .catch(() => {});
            }
            },
        // 多选操作
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        delAllSelection() {
            const length = this.multipleSelection.length;
            let str = '';
            this.delList = this.delList.concat(this.multipleSelection);
            for (let i = 0; i < length; i++) {
                str += this.multipleSelection[i].name + ' ';
            }
            this.$message.error(`删除了${str}`);
            this.multipleSelection = [];
        },

        // 分页导航
        handlePageChange(val) {
            this.$set(this.query, 'pageIndex', val);
            this.getData();
        },
        saveEdit() {
            this.editVisible = false;
            const params = {
                id: this.idx,
                reply: this.form.reply
            };
            axios.post('/manager/notice/reply', params)
                .then(response => {
                this.$message.success(`回覆成功`);
                })
                .catch(error => {
                console.error("回覆失敗: ", error);
                });
        }
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}

</style>
